<?php
require_once 'CMS/Util.php';
require_once 'CMS/Mvc/BaseController.php';
require_once 'CMS/Mvc/BaseUserController.php';
require_once 'CMS/UserCommon.php';
require_once 'CMS/User.php';
require_once 'CMS/Language.php'; //include thu vien language

class QAController extends BaseUserController{

	public function init(){
		parent::init();
		$tbSetting = new User_Model_Parameter();
		$temp = $tbSetting->selectSetting("config");
		$layout = unserialize($temp[0]["parameter_value"]);
		if($layout['config_template'] !="")
		{
			$this->_helper->layout()->setLayout($layout['config_template']);
			$_SESSION['config_template'] = $layout['config_template'];
		}
		else
		{
			$this->_helper->layout()->setLayout('layoutmain');
			$_SESSION['config_template'] = 'layoutmain';
		}
	}
	
	public function categoryAction(){
		$_SESSION['page_code'] = 'qacategory';
		$_GET['type'] = 3;
		
		//Start------Khai báo các parameter
		$dbshow = new User_Model_Parameter();
		//End--------Khai báo các parameter
		
		//Start------get type show
		$code = "Show_".$_SESSION['page_code'];
		$pageshow = $dbshow->selectSetting($code);
		//End--------get type show
		
		$_GET['show'] = $pageshow[0]["parameter_value"]; // khi có click change phần này.... sẽ thay đối số show kiểu list lấy từ xml vào đây
		
		
		$tbSidebarModule = new User_Model_SidebarModule();
		$Modules = $tbSidebarModule->selectAllModule();
		foreach($Modules as $module)
		{
			$database_show_widget [] = $module["module_code"];
			$database_order_widget [$module["module_code"]] =  $module["sort_order"];
		}
		
		$tbDefaultbarModule = new User_Model_DefaultModuleToPage();
		$defaultModules = $tbDefaultbarModule->selectAllModule("qacategory");
		foreach($defaultModules as $dmodule)
		{
			$content_show_widget [] = $dmodule["module_code"];
			$content_order_widget [$dmodule["module_code"]] =  $dmodule["sort_order"];
		}
		
		$tbContentbarModule = new User_Model_ContentModuleToPage();
		// mac dinh homepage
		$ContentModules = $tbContentbarModule->selectAllModule("qacategory");	
		foreach($ContentModules as $cmodule)
		{
			$content_show_widget [] = $cmodule["module_code"];
			$content_order_widget [$cmodule["module_code"]] =  $cmodule["sort_order"];
		}	
		
		$front     = Zend_Controller_Front::getInstance();
		$widgets = $front->getPlugins();
	
		foreach($widgets as $widget)
		{
			if(count($Modules) > 0){
				if($widget->name !="" && in_array($widget->name, $database_show_widget))
				{
					$widget->enable = 1;
					$widget->order = $database_order_widget[$widget->name];
				}
			}
			if(count($content_show_widget) > 0){
				if($widget->name !="" && in_array($widget->name, $content_show_widget))
				{
						$widget->enable = 1;
						$widget->order = $content_order_widget[$widget->name];
				}	
			}		
		}
	}
	
	public function detailAction(){
		$_GET['type'] = 3;
		$_SESSION['page_code'] = 'qadetail';
		
		$tbSidebarModule = new User_Model_SidebarModule();
		$Modules = $tbSidebarModule->selectAllModule();
		foreach($Modules as $module)
		{
			$database_show_widget [] = $module["module_code"];
			$database_order_widget [$module["module_code"]] =  $module["sort_order"];
		}
		
		$tbDefaultbarModule = new User_Model_DefaultModuleToPage();
		$defaultModules = $tbDefaultbarModule->selectAllModule("qadetail");
		foreach($defaultModules as $dmodule)
		{
			$content_show_widget [] = $dmodule["module_code"];
			$content_order_widget [$dmodule["module_code"]] =  $dmodule["sort_order"];
		}
		
		$tbContentbarModule = new User_Model_ContentModuleToPage();
		// mac dinh homepage
		$ContentModules = $tbContentbarModule->selectAllModule("qadetail");	
		foreach($ContentModules as $cmodule)
		{
			$content_show_widget [] = $cmodule["module_code"];
			$content_order_widget [$cmodule["module_code"]] =  $cmodule["sort_order"];
		}	
		
		$front     = Zend_Controller_Front::getInstance();
		$widgets = $front->getPlugins();
	
		foreach($widgets as $widget)
		{
			if(count($Modules) > 0){
				if($widget->name !="" && in_array($widget->name, $database_show_widget))
				{
					$widget->enable = 1;
					$widget->order = $database_order_widget[$widget->name];
				}
			}
			if(count($content_show_widget) > 0){
				if($widget->name !="" && in_array($widget->name, $content_show_widget))
				{
						$widget->enable = 1;
						$widget->order = $content_order_widget[$widget->name];
				}	
			}		
		}
	}
	
	public function postAction(){
		
		
		/*========== Start Load Language ==========*/
			$language = new Language(APPLICATION_PATH . '/modules/user/languages/qa');
			if(isset($_SESSION['language']))
			{
				$language_id = $_SESSION['language'];
				$tbLanguage = new Language_Model_Language();
				$name = $tbLanguage->getNameLanguage($language_id);
				$language->load($name['name']);
			}
			else
				$language->load('Default');		
				
			$languages = $tbLanguage->getAllLanguages();
			$this->view->languages = $languages;
			/*========== End Load Language ==========*/
				
			/*========== Start Get Text ==============*/
			$this->view->textTitle 		= $language->get('text_title');
			$this->view->texttieude 		= $language->get('text_tieude');
			$this->view->text_price		= $language->get('text_price');
			$this->view->textDMO 		= $language->get('text_dmo');
			$this->view->textND 		= $language->get('text_nd');
			$this->view->textbutton 		= $language->get('text_button');
			
			$this->view->textError1 	= $language->get('error1');
			$this->view->textError2 	= $language->get('error2');
			$this->view->textError3 	= $language->get('error3');
			$this->view->textError4 	= $language->get('error4');
			$this->view->textError5 	= $language->get('error5');
			$this->view->textError6 	= $language->get('error6');
			/*========== End Text ==============*/		
		
		
		$this->_helper->layout->disableLayout();
		//$_SESSION["id_user"] = 1;//test user dang nhap
		
		//Start------Khai báo các parameter
		$tbcategory = new User_Model_Categories();
		$tbthings = new User_Model_Things();
		$dateInt = new Util();
		$tbuser = new User_Model_Users();
		//End--------Khai báo các parameter
		
		$path = APPLICATION_PATH."/widgets/lastestqa/";
		$xmlconfig = new SimpleXMLElement($path."config.xml",null,true);//Read config.xml
		$user = new User();
		$user->init();
		$user->check_login();
		$hasmodify = $user->modifiy_content($xmlconfig->name);
		if($hasmodify=="false")
		{
			$data=-10;
			$this->view->error = 6;
			return;	
		}
		else
		{
		
			
			//Start------Check Input Parameter
			$session = new Zend_Session_Namespace('login.auth');
			if(!isset($session->id_user))
			{
				$this->view->error = 5;
			}
			else 
			{
				//Start------Get user
				$user = $tbuser->selectUser($session->id_user);
				//End--------Get user
			}
			if(isset($_SESSION["PostQA_Error"]))
			{
				$this->view->error = $_SESSION["PostQA_Error"];
				unset($_SESSION["PostQA_Error"]);
			}
			if(isset($_GET["action"])&&($_GET["action"]=="new")&&(!isset($this->view->error)))
			{
				if(!isset($_POST["QA_category"])||(!is_numeric($_POST["QA_category"]))||($_POST["QA_category"]<=0))
				{
					$this->view->error = 3;
				}
				
				$error_desc = array();
				
				//check multi-language
				if(!isset($_POST["QA_title"]['Default'])||(strlen($_POST["QA_title"]['Default'])<10))
				{
					$this->view->error = 2;
					$error_desc['Default'][0] = $language->get('error2');
				}
				if(!isset($_POST["QA_description"]['Default'])||(strlen($_POST["QA_description"]['Default'])<20))
				{
					$this->view->error = 4;
					$error_desc['Default'][1] = $language->get('error4');
				}
				
				foreach($languages as $lang){
					if(!isset($_POST["QA_title"][$lang['name']])||(strlen($_POST["QA_title"][$lang['name']])<10))
					{
						$this->view->error = 2;
						$error_desc[$lang['name']][0] = $language->get('error2');
					}
					if(!isset($_POST["QA_description"][$lang['name']])||(strlen($_POST["QA_description"][$lang['name']])<20))
					{
						$this->view->error = 4;
						$error_desc[$lang['name']][1] = $language->get('error4');
					}
				}
				
				$this->view->error_desc = $error_desc;
				
			}
			//End--------Check Input Parameter
			
			
			
			//Start------Get QA Category
			//$CategoriesQA = $tbcategory->getLeafCategoriesbyType(3);
			$category=$tbcategory->getLeafCategoriesbyType(3);
			$CategoriesQA = array();
			foreach ($category as $pcate){
					$nameCate = unserialize($pcate['category_name']);
					if(isset($nameCate[$name['name']]) && isset($name)){
						$category_name = $nameCate[$name['name']];
					}else{
						$category_name = $nameCate['Default'];
					}
					$CategoriesQA[] = array(
										'category_id'	=>	$pcate['category_id'],
										'category_code'	=>	$pcate['category_code'],
										'category_name'	=>	$category_name,
										'parent_id'		=>	$pcate['parent_id'],
										'is_leaf'		=>	$pcate['is_leaf'],
										'type'			=>	$pcate['type']
										);
			}
			//End--------Get QA Category
			
			if(isset($_GET["action"])&&($_GET["action"]=="new")&&(!isset($this->view->error)))
			{
				//get all languages
				$tbLanguage = new Language_Model_Language();
				$all_languages= $tbLanguage->getAllLanguages();
				//end get
				
				//insert title and decription into all languages
				$title_lang["Default"]="...";
				$description_lang["Default"]="-----------------------";
				$common_info_lang["Default"]="-----------------------";
				$short_des_lang["Default"]="-----------------------";
				if(isset($_POST["QA_title"]["Default"]))
					$title_lang["Default"]=$_POST["QA_title"]["Default"];
				if(isset($_POST["QA_description"]["Default"]))
				{
					$description_lang["Default"]=$_POST["QA_description"]["Default"];
					$short_des_lang["Default"]=substr($_POST["QA_description"]["Default"],0,50);
					$common_info_lang["Default"]=substr($_POST["QA_description"]["Default"],0,50);
				}
				
				foreach ($all_languages as $lang)
				{
					$title_lang[$lang["name"]]="...";
					$description_lang[$lang["name"]]="-----------------------";
					$short_des_lang[$lang["name"]]="-----------------------";
					$common_info_lang[$lang["name"]]="-----------------------";
					
					if(isset($_POST["QA_title"][$lang["name"]]))
						$title_lang[$lang["name"]]=$_POST["QA_title"][$lang["name"]];
					if(isset($_POST["QA_description"][$lang["name"]]))
					{
						$description_lang[$lang["name"]]=$_POST["QA_description"][$lang["name"]];
						$short_des_lang[$lang["name"]]=substr($_POST["QA_description"][$lang["name"]],0,50);
						$common_info_lang[$lang["name"]]=substr($_POST["QA_description"][$lang["name"]],0,50);
					}
					
				}
				//end insert
				
				$inserData = array(
									'category_id'	=>	$_POST["QA_category"],
									'user_id'		=>	$session->id_user,
									'title'			=>	serialize($title_lang),//$_POST["QA_title"],
									'description'	=>	serialize($description_lang),//html_entity_decode($_POST["QA_description"]),
									'type'			=>	3,
									'views'			=>	0,
									'created_date'	=>	$dateInt->get_time_now(),
									'update_date'	=>	$dateInt->get_time_now(),
									'deleted'		=>	0,
									'avatar'		=>	$user[0]["avatar"],
									'common_info'	=>	serialize($common_info_lang),//substr($_POST["QA_description"],0,50),
									'short_description'=> serialize($short_des_lang),//substr($_POST["QA_description"],0,50)
									);
				$result = $tbthings->insertThings($inserData);
				$this->view->error = $result;
			}
			if(isset($_POST["QA_title"]))
			{
				$this->view->title = $_POST["QA_title"];
			}
			else 
			{
				$this->view->title = "";
			}
			if(isset($_POST["QA_category"]))
			{
				$this->view->category = $_POST["QA_category"];
			}
			else 
			{
				$this->view->category = 0;
			}
			if(isset($_POST["QA_description"]))
			{
				$this->view->description = $_POST["QA_description"];
			}
			else 
			{
				$this->view->description = "";
			}
			//Start------Truyền parameter qua View
			if(count($CategoriesQA)>0)
			{
				$this->view->CategoriesQA = $CategoriesQA;
			}
			else 
			{
				$this->view->CategoriesQA = array();
			}
			//End--------Truyền parameter qua View
		}
		
	}
	
	//Action Switch Type Show xử lý chức năng thay đổi phương thức hiển thị hỏi đáp
	public function switchtypeshowAction(){
		$this->_helper->layout->disableLayout();
		
		if(count($_GET) && isset($_GET["typeshow"]) && is_numeric($_GET["typeshow"]) && $_GET["typeshow"]>0) 
		{
			$typeshow = $_GET["typeshow"];
			$data=array(
				'parameter_name' 	=> "Show_qacategory",
				'parameter_value' 	=> $typeshow
			);
			
			//Start------Khai báo các parameter
			$dbshow = new User_Model_Parameter();
			//End--------Khai báo các parameter
			
			//Start------Cập nhật phương thức hiển thị
			$result = $dbshow->updateSetting($data);
			//End--------Cập nhật phương thức hiển thị
			
			$this->_helper->json(1);
		}
		else {
			$this->_helper->json(-1);
		}
	}
}